import java.util.LinkedList;
import java.util.Queue;

//01 矩阵
//测试链接：https://leetcode.cn/problems/01-matrix/
public class UpdateMatrix {
    int[] dx = {-1,1,0,0};
    int[] dy = {0,0,-1,1};
    int m, n;
    public int[][] updateMatrix1(int[][] mat) {
        m = mat.length; n = mat[0].length;
        int[][] ans = new int[m][n];
        boolean[][] vis = new boolean[m][n];  //用来标记当前位置是否以及搜索过

        Queue<int[]> q = new LinkedList<>();
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                if(mat[i][j] == 0) {
                    ans[i][j] = 0;
                    vis[i][j] = true;
                    q.add(new int[]{i,j});
                }
            }
        }

        int step = 0;
        while(!q.isEmpty()) {
            step++;
            int size = q.size();
            while(size-- >0) {
                int[] t = q.poll();
                int a = t[0], b = t[1];

                for(int i = 0; i < 4; i++) {
                    int x = a + dx[i], y = b + dy[i];
                    if(x>=0 && x<m && y>=0 && y<n && !vis[x][y] && mat[x][y]==1) {
                        ans[x][y] = step;
                        vis[x][y] = true;
                        q.add(new int[]{x,y});
                    }
                }
            }
        }

        return ans;
    }

    public int[][] updateMatrix2(int[][] mat) {
        m = mat.length;
        n = mat[0].length;
        //ans[][] == -1  表示未被查找到
        //ans[][] != -1  表示与0的距离
        int[][] ans = new int[m][n];

        Queue<int[]> q = new LinkedList<>();
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++) {
                if (mat[i][j] == 0) {
                    ans[i][j] = 0;
                    q.add(new int[] { i, j });
                }else {
                    ans[i][j] = -1;
                }
            }
        }
        while (!q.isEmpty()) {
            int[] t = q.poll();
            int a = t[0], b = t[1];

            for (int i = 0; i < 4; i++) {
                int x = a + dx[i], y = b + dy[i];
                if (x >= 0 && x < m && y >= 0 && y < n && ans[x][y] == -1) {
                    ans[x][y] = ans[a][b] + 1;
                    q.add(new int[] { x, y });
                }
            }

        }

        return ans;
    }
}
